﻿using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Mvc;
using WikeSoft.WorkFlowEngine.Enum;
using WikeSoft.WorkFlowEngine.Filter;
using WikeSoft.WorkFlowEngine.Interfaces;
using WikeSoft.WorkFlowEngine.Models;

namespace WikeSoft.Web.Controllers.WorkFlow
{
    public class WorkFlowInstanceController : BaseController
    {
        private IWorkFlowInstanceService _workFlowInstanceService;
        private readonly IWorkFlowInstanceService _flowInstanceService;
        public WorkFlowInstanceController(IWorkFlowInstanceService workFlowInstanceService, IWorkFlowInstanceService flowInstanceService)
        {
            _workFlowInstanceService = workFlowInstanceService;
            _flowInstanceService = flowInstanceService;
        }

        // GET: WorkFlowInstance
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult HistoryInstanceView()
        {
            return View();
        }


        [HttpGet]
        public JsonResult Query(WorkFlowInstanceFilter filter)
        {
            var result = _workFlowInstanceService.Query(filter);
            return JsonOk(result);
        }

        [HttpGet]
        public JsonResult QueryHistory(WorkFlowInstanceFilter filter)
        {
            filter.AssociatedUserId = User.Identity.GetLoginUserId().ToString().ToUpper();
            var result = _workFlowInstanceService.Query(filter);
            return JsonOk(result);
        }

        public ActionResult GetTaskView( string instanceId)
        {

            List<TaskInstance> flows = _flowInstanceService.GetHistoryFlowInstances(instanceId);
            ViewBag.Historys = flows;
            return View();
        }

        public ActionResult WaitToDoList()
        {
            return View();
        }

        public ActionResult QueryWaitToDoList(WorkFlowInstanceFilter filter)
        {
            filter.AssociatedUserId = User.Identity.GetLoginUserId().ToString().ToUpper();
            filter.FlowRunStatus = FlowRunStatus.Run;
            
            var result = _workFlowInstanceService.Query(filter);
            return JsonOk(result);
        }

        public void Pic(string flowId)
        {
            var image = _flowInstanceService.GetRunBitmap(flowId);
            MemoryStream stream = new MemoryStream();
            image.Save(stream, ImageFormat.Jpeg);
            HttpContext.Response.Clear();
            HttpContext.Response.ContentType = "image/jpeg";
            HttpContext.Response.BinaryWrite(stream.ToArray());

        }
    }
}